<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\logic\Product as CommonProduct;
use app\common\logic\Price as CommonPrice;

/**
 * 产品管理逻辑
 */
class Product extends AdminBase
{
    
    public static $commonProductLogic = null;
    public static $commonPriceLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonProductLogic) && static::$commonProductLogic = new CommonProduct();
        empty(static::$commonPriceLogic) && static::$commonPriceLogic = new CommonPrice();
    }

    /**
     * 获取添加/编辑商品分类
     */
    public function productAddEditCommon()
    {
        return $this->modelProduct->base['categories'];
    }
    
    /**
     * 获取产品列表搜索条件
     * @param array $data 搜索参数
     * @return array
     */
    public function getWhere($data = [])
    {
        return static::$commonProductLogic->getWhere($data);
    }
    
    /**
     * 获取产品列表
     */
    public function getProductList($where = [], $field = 's.*,pic.path as cover', $order = 's.id desc', $paginate = DB_LIST_ROWS)
    {
        return static::$commonProductLogic->getProductList($where, $field, $order, $paginate);
    }
    
    /**
     * 获取产品信息
     */
    public function getProductInfo($where = [], $field = true)
    {
        $info = static::$commonProductLogic->getProductInfo($where, $field);

        return $info;
    }
    
    /**
     * 添加产品
     */
    public function productAdd($data = [])
    {
        $url = url('productlist');
        
        $validate_result = $this->validateProduct->scene('add')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateProduct->getError()];
        }
        
        // 使用事务确保商品添加和价格记录的一致性
        $result = \think\facade\Db::transaction(function () use ($data) {
            // 添加商品
            $productId = $this->modelProduct->setInfo($data);
            
            if (!$productId) {
                return false;
            }
            
            // 记录初始价格到价格历史表
            if (!empty($data['market_price'])) {
                $priceData = [
                    'product_id' => $productId,
                    'price' => $data['market_price'],
                    'price_date' => date('Y-m-d'),
                    'create_time' => time(),
                    'update_time' => time(),
                    'status' => 1
                ];
                
                // 调用common层的价格逻辑添加价格记录
                $priceResult = static::$commonPriceLogic->priceAdd($priceData);
                
                if (is_array($priceResult) && $priceResult[0] == RESULT_ERROR) {
                    return false;
                }
            }
            
            return $productId;
        });
        
        if ($result) {
            action_log('新增', '新增产品，标题：' . $data['name']);
            return [RESULT_SUCCESS, '添加成功', $url];
        } else {
            return [RESULT_ERROR, '添加失败'];
        }
    }
    
    /**
     * 编辑产品
     */
    public function productEdit($data = [])
    {
        $url = url('productlist');
        
        $validate_result = $this->validateProduct->scene('edit')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateProduct->getError()];
        }
        
        $result = static::$commonProductLogic->productEdit($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('编辑', '编辑产品，id：' . $data['id']);
        
        return [RESULT_SUCCESS, '编辑成功', $url];
    }
    
    /**
     * 删除产品
     */
    public function productDel($data = [])
    {
        $url = url('productlist');
        
        if (empty($data['id'])) {
            return [RESULT_ERROR, '参数错误'];
        }
        
        $result = static::$commonProductLogic->productDel($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('删除', '删除产品，id：' . $data['id']);
        
        return [RESULT_SUCCESS, '删除成功', $url];
    }
    
    /**
     * 产品状态切换
     */
    public function productStatus($data = [])
    {
        $url = url('productlist');
        
        if (empty($data['id'])) {
            return [RESULT_ERROR, '参数错误'];
        }
        
        $result = static::$commonProductLogic->productStatus($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('状态', '切换产品状态，id：' . $data['id']);
        
        return [RESULT_SUCCESS, '操作成功', $url];
    }
    
    /**
     * 导出产品列表
     */
    public function exportProductList($where = [], $field = true, $order = 'sort desc,id desc')
    {
        $list = static::$commonProductLogic->getProductListForAdmin($where, $field, $order, false);
        
        $titles = "产品标题,分类,价格,状态,创建时间";
        $keys   = "title,category_name,price,status_text,create_time";
        
        action_log('导出', '导出产品列表');
        
        export_excel($titles, $keys, $list, '产品列表');
    }
    
    /**
     * 分类管理
     */
    public function categoryManage($data = [])
    {
        $url = url('category');
        
        $result = static::$commonProductLogic->categoryManage($data);
        
        if (is_array($result) && $result[0] == RESULT_ERROR) {
            return $result;
        }
        
        action_log('分类', '产品分类管理');
        
        return [RESULT_SUCCESS, '操作成功', $url];
    }
    
    /**
     * 获取分类列表
     */
    public function getCategoryList($where = [], $field = true, $order = 'sort desc,id desc')
    {
        return static::$commonProductLogic->getCategoryList($where, $field, $order);
    }
    

    
    /**
     * 商品库存管理
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function stockManage($data = [])
    {
        return static::$commonProductLogic->stockManage($data);
    }

    /**
     * 获取商品详情（后台编辑专用）
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getProductDetail($data = [])
    {
        $id = $data['id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        // 获取商品基本信息
        $info = $this->modelProduct->getInfo(['id' => $id]);
        
        if (empty($info)) {
            return [RESULT_ERROR, '商品不存在'];
        }
        
        return [RESULT_SUCCESS, '获取成功', $info];
    }
    
    /**
     * 商品导入处理
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function productImport($data = [])
    {
        $url = url('productimport');
        
        // 检查是否有上传文件
        if (empty($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
            return [RESULT_ERROR, '请选择要导入的Excel文件'];
        }
        
        $file = $_FILES['import_file'];
        
        // 验证文件类型
        $allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
        if (!in_array($file['type'], $allowedTypes)) {
            return [RESULT_ERROR, '文件格式不正确，请上传Excel文件'];
        }
        
        // 验证文件大小（限制10MB）
        if ($file['size'] > 10 * 1024 * 1024) {
            return [RESULT_ERROR, '文件大小不能超过10MB'];
        }
        
        try {
            // 生成批次ID
            $batchId = date('YmdHis') . rand(1000, 9999);
            
            // 记录导入日志
            $logData = [
                'batch_id' => $batchId,
                'filename' => $file['name'],
                'file_size' => $file['size'],
                'import_status' => 'processing',
                'operator_id' => session('member_id'),
                'operator_name' => session('member_name'),
                'create_time' => time(),
                'start_time' => time()
            ];
            
            $logId = $this->modelProductImportLog->save($logData);
            
            if (!$logId) {
                return [RESULT_ERROR, '创建导入日志失败'];
            }
            
            // 解析Excel文件
            $result = $this->parseExcelFile($file['tmp_name'], $batchId);
            
            if ($result[0] == RESULT_ERROR) {
                // 更新导入日志为失败状态
                $this->modelProductImportLog->updateInfo(['id' => $logId], [
                    'import_status' => 'failed',
                    'error_message' => $result[1],
                    'end_time' => time(),
                    'duration' => time() - $logData['start_time']
                ]);
                
                return $result;
            }
            
            // 执行数据导入
            $importResult = $this->executeImport($batchId, $logId);
            
            if ($importResult[0] == RESULT_ERROR) {
                return $importResult;
            }
            
            action_log('导入', '商品批量导入，批次ID：' . $batchId);
            
            return [RESULT_SUCCESS, '导入完成，' . $importResult[1], $url];
            
        } catch (\Exception $e) {
            // 更新导入日志为失败状态
            if (isset($logId)) {
                $this->modelProductImportLog->updateInfo(['id' => $logId], [
                    'import_status' => 'failed',
                    'error_message' => $e->getMessage(),
                    'end_time' => time(),
                    'duration' => time() - $logData['start_time']
                ]);
            }
            
            return [RESULT_ERROR, '导入失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 解析Excel文件
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function parseExcelFile($filePath, $batchId)
    {
        try {
            // 使用PhpSpreadsheet解析Excel
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($filePath);
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($filePath);
            $worksheet = $spreadsheet->getActiveSheet();
            
            $rows = $worksheet->toArray();
            
            if (empty($rows) || count($rows) < 2) {
                return [RESULT_ERROR, 'Excel文件内容为空或格式不正确'];
            }
            
            // 验证表头
            $header = $rows[0];
            $expectedHeader = ['商品名称', '分类', '品牌', '规格', '原价', '现价', '会员价', '图片URL', '是否VIP专享', '排序', '状态'];
            
            if (count($header) < count($expectedHeader)) {
                return [RESULT_ERROR, '表头格式不正确，请下载最新模板'];
            }
            
            $totalRows = count($rows) - 1; // 减去表头行
            $validRows = 0;
            $errorRows = 0;
            
            // 逐行解析数据
            for ($i = 1; $i < count($rows); $i++) {
                $row = $rows[$i];
                $rowNum = $i + 1;
                
                // 跳过空行
                if (empty(array_filter($row))) {
                    continue;
                }
                
                $validationResult = $this->validateImportRow($row, $rowNum);
                
                $tempData = [
                    'batch_id' => $batchId,
                    'row_number' => $rowNum,
                    'name' => trim($row[0] ?? ''),
                    'category' => trim($row[1] ?? ''),
                    'brand' => trim($row[2] ?? ''),
                    'specification' => trim($row[3] ?? ''),
                    'original_price' => floatval($row[4] ?? 0),
                    'current_price' => floatval($row[5] ?? 0),
                    'vip_price' => floatval($row[6] ?? 0),
                    'image_url' => trim($row[7] ?? ''),
                    'is_vip_only' => $this->parseVipOnly($row[8] ?? ''),
                    'sort' => intval($row[9] ?? 0),
                    'status' => $this->parseStatus($row[10] ?? ''),
                    'validation_status' => $validationResult['status'],
                    'validation_message' => $validationResult['message'],
                    'import_status' => 'pending',
                    'create_time' => time()
                ];
                
                // 保存到临时表
                $this->modelProductImportTemp->save($tempData);
                
                if ($validationResult['status'] == 'valid') {
                    $validRows++;
                } else {
                    $errorRows++;
                }
            }
            
            return [RESULT_SUCCESS, '解析完成', [
                'total_rows' => $totalRows,
                'valid_rows' => $validRows,
                'error_rows' => $errorRows
            ]];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '文件解析失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 验证导入行数据
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function validateImportRow($row, $rowNum)
    {
        $errors = [];
        
        // 商品名称必填
        if (empty(trim($row[0] ?? ''))) {
            $errors[] = '商品名称不能为空';
        }
        
        // 分类必填
        if (empty(trim($row[1] ?? ''))) {
            $errors[] = '分类不能为空';
        }
        
        // 价格验证
        $originalPrice = floatval($row[4] ?? 0);
        $currentPrice = floatval($row[5] ?? 0);
        $vipPrice = floatval($row[6] ?? 0);
        
        if ($originalPrice < 0) {
            $errors[] = '原价不能为负数';
        }
        
        if ($currentPrice <= 0) {
            $errors[] = '现价必须大于0';
        }
        
        if ($vipPrice < 0) {
            $errors[] = 'VIP价格不能为负数';
        }
        
        if ($currentPrice > $originalPrice && $originalPrice > 0) {
            $errors[] = '现价不能高于原价';
        }
        
        // 状态验证
        $status = trim($row[10] ?? '');
        if (!in_array($status, ['启用', '禁用', '1', '0', ''])) {
            $errors[] = '状态值无效，请填写"启用"或"禁用"';
        }
        
        // VIP专享验证
        $isVipOnly = trim($row[8] ?? '');
        if (!in_array($isVipOnly, ['是', '否', '1', '0', ''])) {
            $errors[] = 'VIP专享值无效，请填写"是"或"否"';
        }
        
        if (empty($errors)) {
            return ['status' => 'valid', 'message' => ''];
        } else {
            return ['status' => 'invalid', 'message' => implode('; ', $errors)];
        }
    }
    
    /**
     * 解析VIP专享字段
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function parseVipOnly($value)
    {
        $value = trim($value);
        if (in_array($value, ['是', '1'])) {
            return 1;
        }
        return 0;
    }
    
    /**
     * 解析状态字段
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function parseStatus($value)
    {
        $value = trim($value);
        if (in_array($value, ['启用', '1']) || empty($value)) {
            return 1;
        }
        return 0;
    }
    
    /**
     * 执行数据导入
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function executeImport($batchId, $logId)
    {
        try {
            // 获取有效的导入数据
            $tempList = $this->modelProductImportTemp->getList([
                'batch_id' => $batchId,
                'validation_status' => 'valid'
            ], true, 'row_number asc', false);
            
            $successCount = 0;
            $failCount = 0;
            
            foreach ($tempList as $item) {
                try {
                    // 检查商品名称是否已存在
                    $existProduct = $this->modelProduct->getInfo(['name' => $item['name']]);
                    
                    if ($existProduct) {
                        // 更新临时表状态
                        $this->modelProductImportTemp->updateInfo(['id' => $item['id']], [
                            'import_status' => 'failed',
                            'import_message' => '商品名称已存在'
                        ]);
                        $failCount++;
                        continue;
                    }
                    
                    // 准备商品数据
                    $productData = [
                        'name' => $item['name'],
                        'category' => $item['category'],
                        'brand' => $item['brand'],
                        'specification' => $item['specification'],
                        'original_price' => $item['original_price'],
                        'current_price' => $item['current_price'],
                        'vip_price' => $item['vip_price'],
                        'image_url' => $item['image_url'],
                        'is_vip_only' => $item['is_vip_only'],
                        'sort' => $item['sort'],
                        'status' => $item['status'],
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    
                    // 插入商品数据
                    $productId = $this->modelProduct->save($productData);
                    
                    if ($productId) {
                        // 更新临时表状态
                        $this->modelProductImportTemp->updateInfo(['id' => $item['id']], [
                            'import_status' => 'success',
                            'import_message' => '导入成功',
                            'product_id' => $productId
                        ]);
                        $successCount++;
                    } else {
                        // 更新临时表状态
                        $this->modelProductImportTemp->updateInfo(['id' => $item['id']], [
                            'import_status' => 'failed',
                            'import_message' => '数据库插入失败'
                        ]);
                        $failCount++;
                    }
                    
                } catch (\Exception $e) {
                    // 更新临时表状态
                    $this->modelProductImportTemp->updateInfo(['id' => $item['id']], [
                        'import_status' => 'failed',
                        'import_message' => $e->getMessage()
                    ]);
                    $failCount++;
                }
            }
            
            // 更新导入日志
            $this->modelProductImportLog->updateInfo(['id' => $logId], [
                'total_rows' => count($tempList),
                'success_rows' => $successCount,
                'failed_rows' => $failCount,
                'import_status' => 'completed',
                'import_summary' => "成功导入{$successCount}条，失败{$failCount}条",
                'end_time' => time(),
                'duration' => time() - time()
            ]);
            
            return [RESULT_SUCCESS, "成功导入{$successCount}条商品，失败{$failCount}条"];
            
        } catch (\Exception $e) {
            // 更新导入日志为失败状态
            $this->modelProductImportLog->updateInfo(['id' => $logId], [
                'import_status' => 'failed',
                'error_message' => $e->getMessage(),
                'end_time' => time(),
                'duration' => time() - time()
            ]);
            
            return [RESULT_ERROR, '导入执行失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取导入历史记录
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getImportLogs($where = [], $field = true, $order = 'id desc', $paginate = ['list_rows' => 10])
    {
        return $this->modelProductImportLog->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 下载导入模板
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function downloadImportTemplate()
    {
        $headers = ['商品名称', '分类', '品牌', '规格', '原价', '现价', '会员价', '图片URL', '是否VIP专享', '排序', '状态'];
        $sampleData = [
            ['示例商品1', '电子产品', '苹果', 'iPhone 15 128GB', '6999.00', '6499.00', '6299.00', 'https://example.com/image1.jpg', '否', '100', '启用'],
            ['示例商品2', '服装', '耐克', 'Air Max 270 42码', '899.00', '799.00', '749.00', 'https://example.com/image2.jpg', '是', '90', '启用']
        ];
        
        // 创建Excel文件
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        
        // 设置表头
        $worksheet->fromArray($headers, null, 'A1');
        
        // 设置样例数据
        $worksheet->fromArray($sampleData, null, 'A2');
        
        // 设置列宽
        foreach (range('A', 'K') as $col) {
            $worksheet->getColumnDimension($col)->setAutoSize(true);
        }
        
        // 设置表头样式
        $headerStyle = [
            'font' => ['bold' => true],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'E6E6FA']
            ]
        ];
        $worksheet->getStyle('A1:K1')->applyFromArray($headerStyle);
        
        // 输出文件
        $filename = '商品导入模板_' . date('YmdHis') . '.xlsx';
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        
        action_log('下载', '下载商品导入模板');
        
        exit;
    }
    
    /**
     * 获取导入进度
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getImportProgress($data = [])
    {
        $batchId = $data['batch_id'] ?? '';
        
        if (empty($batchId)) {
            return [RESULT_ERROR, '批次ID不能为空'];
        }
        
        $log = $this->modelProductImportLog->getInfo(['batch_id' => $batchId]);
        
        if (empty($log)) {
            return [RESULT_ERROR, '导入记录不存在'];
        }
        
        return [RESULT_SUCCESS, '获取成功', $log];
    }
    
    /**
     * 获取导入详情
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getImportDetail($data = [])
    {
        $batchId = $data['batch_id'] ?? '';
        
        if (empty($batchId)) {
            return [RESULT_ERROR, '批次ID不能为空'];
        }
        
        $tempList = $this->modelProductImportTemp->getList([
            'batch_id' => $batchId
        ], true, 'row_number asc', false);
        
        return [RESULT_SUCCESS, '获取成功', $tempList];
    }
    
    /**
     * 获取产品统计数据
     */
    public function getProductStats()
    {
        // 总产品数
        $totalProducts = $this->modelProduct->stat(['status' => 1], 'count');
        
        // 今日新增产品
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        $todayNewProducts = $this->modelProduct->stat([
            'create_time' => ['between', [$todayStart, $todayEnd]],
            'status' => 1
        ], 'count');
        
        // 热门产品（按关注数排序，取前5个）
        $popularProducts = $this->modelProduct->getList(
            ['status' => 1], 
            'id, name, follow_count', 
            'follow_count desc', 
            ['list_rows' => 5]
        );
        
        return [
            'total_products' => $totalProducts,
            'today_new_products' => $todayNewProducts,
            'popular_products' => $popularProducts
        ];
    }
}